<template>
  <div
    class="projectEdit route-page"
    :class="$store.getters.isMobile ? 'isMobile' : ''"
  >
    <section class="header">
      <a-page-header :title="title" @back="goBack" />
    </section>
    <section class="content">
      <a-form layout="vertical">
        <a-card title="基础信息" :bordered="false">
          <a-row :gutter="[24, 8]">
            <a-col :span="8">
              <a-form-item v-bind="validateInfos.name">
                <template #label>
                  <span>{{ $L("项目名称") }}</span>
                </template>
                <a-input
                  :placeholder="namePlaceholder"
                  v-model:value="modelRef.name"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item v-bind="validateInfos.short_name">
                <template #label>
                  <span style="margin-right: 5px">{{ $L("项目简称") }}</span>
                  <a-tooltip>
                    <template #title
                      >通常用来显示完整信息、注释信息、辅助提示。</template
                    >
                    <QuestionCircleOutlined />
                  </a-tooltip>
                  <span></span>
                </template>
                <a-input
                  :placeholder="placeholderShortName"
                  v-model:value="modelRef.short_name"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="所属地区" v-bind="validateInfos.area">
                <a-cascader
                  v-model:value="modelRef.area"
                  :options="areaOptions"
                  :load-data="loadAreaData"
                  placeholder="请选择所属地区"
                  change-on-select
                  @change="areaSelectChange"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="详细地址" v-bind="validateInfos.address">
                <!-- <a-button type="link">选取位置</a-button> -->
                <div
                  class="detail-address"
                  @click="onAddressSearch"
                  :style="{
                    backgroundColor: !systemOnIntranet ? '#fff' : '#f5f5f5',
                    cursor: !systemOnIntranet ? 'pointer' : 'default',
                  }"
                >
                  <text v-if="modelRef.address">
                    {{ modelRef.address }}
                  </text>
                  <text class="placeholder" v-else>
                    点击打开地图选取详细地址
                  </text>
                </div>
                <!-- <a-input-search
                  placeholder="请输入详细地址"
                  v-model:value="modelRef.address"
                  @search="onAddressSearch"
                /> -->
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item v-bind="validateInfos.tag_id_arr">
                <template #label>
                  <span>{{ $L("项目") }}标签</span>
                </template>
                <a-select
                  v-model:value="modelRef.tag_id_arr"
                  :options="projectTags"
                  mode="multiple"
                  :placeholder="placeholderTag"
                >
                  <template #dropdownRender="{ menuNode: menu }">
                    <v-nodes :vnodes="menu" />
                    <a-divider style="margin: 4px 0" />

                    <!--@mousedown="e => e.preventDefault()"  -->
                    <div
                      style="
                        padding: 4px 8px;
                        cursor: pointer;
                        color: #1890ff;
                        text-align: center;
                      "
                      @mousedown="(e) => e.preventDefault()"
                      @click="addTag"
                    >
                      <!-- <plus-outlined /> -->
                      添加
                    </div>
                  </template>
                </a-select>
              </a-form-item>
            </a-col>
       
            <a-col :span="8">
              <a-form-item label="用户端是否展示">
                <a-switch v-model:checked="modelRef.user_show" checked-children="展示" un-checked-children="隐藏" :checkedValue="1" :unCheckedValue="0" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item v-bind="validateInfos.describe">
                <template #label>
                  <span>{{ $L("项目简介	") }}</span>
                </template>
                <a-textarea
                  v-model:value="modelRef.describe"
                  :placeholder="placeholderEextarea"
                  :rows="3"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>

        <a-card title="楼宇管理" :bordered="false" class="mt-20" v-if="!id">
          <section class="flex flex-wrap">
            <div
              class="building-card"
              v-for="(building, index) of buildingList"
              :key="building.number"
              @click="addBuilding(index)"
            >
              <div class="title">
                {{ building.name }}
              </div>
              <div class="desc">{{ building.layerList.length + "层" }}</div>
            </div>
            <div class="add-btn" @click="addBuilding()">
              <PlusOutlined />
            </div>
          </section>
        </a-card>
        <a-card :bordered="false" class="mt-20">
          <template #title>
            <span class="collapseTitle">图片</span>
            <span class="collapseTitleSub"
              >推荐上传16：9比例的图片, 可以拖动改变图片排序</span
            >
          </template>
          <section style="display: flex; align-items: center; flex-wrap: wrap">
            <draggable
              class="list-group"
              tag="transition-group"
              :component-data="{
                tag: 'ul',
                type: 'transition-group',
                name: !drag ? 'flip-list' : null,
              }"
              v-model="sortList"
              v-bind="dragOptions"
              @start="drag = true"
              @end="drag = false"
              item-key="index"
            >
              <template #item="{ element, index }">
                <li class="list-group-item">
                  <img :src="element.url" class="imgae" />
                  <span class="list-group-icon" @click="deleClick(index)"
                    ><CloseOutlined class="icon"
                  /></span>
                </li>
              </template>
            </draggable>
            <image-cropper
              style="margin-bottom: 20px"
              ref="imageCropper"
              :options="cropperOptions"
              @crop-upload-success="cropSuccess"
              @remove="removeImage"
              :imageNumber="9"
            />
          </section>

          <!-- <a-upload
            :action="$utils.imgAction"
            :headers="{ 'org-token': $store.getters.token }"
            :multiple="false"
            v-model:file-list="logoList"
            @change="uploadLogo"
            name="image"
            :data="{ dir: 'org_village_building' }"
            accept="image/jpg,image/jpeg,image/gif,image/png"
            list-type="picture-card"
            @preview="handlePreview"
            @remove="removeClick"
          >
            <div v-if="logoList.length < 1">
              <PlusOutlined />
            </div>
          </a-upload> -->
          <a-modal
            :visible="previewVisible"
            :footer="null"
            @cancel="handleCancel"
          >
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </a-card>
        <a-card :bordered="false" class="mt-20">
          <a-collapse
            v-model:activeKey="activeKey"
            expandIconPosition="right"
            :bordered="false"
          >
            <a-collapse-panel key="1">
              <template #header>
                <span class="collapseTitle">拓展信息</span>
                <span class="collapseTitleSub"
                  >拓展信息将用于在招商平台展示，当无需使用招商平台时可以不进行填写</span
                >
              </template>
              <a-row :gutter="[24, 24]">
                <a-col :span="$store.getters.isMobile ? 24 : 6">
                  <a-form-item>
                    <template #label>
                      <span style="margin-right: 5px">VR链接</span>
                      <a-tooltip>
                        <template #title>输入后默认支持VR展示</template>
                        <QuestionCircleOutlined />
                      </a-tooltip>
                    </template>
                    <a-input v-model:value="modelRef.vr_link" />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 6">
                  <a-form-item label="排序值">
                    <a-input-number
                      style="width: 100%"
                      id="inputNumber"
                      :min="0"
                      :precision="0"
                      v-model:value="modelRef.sort"
                      placeholder="排序值越大展示越靠前"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 6">
                  <a-form-item label="竣工时间">
                    <a-date-picker
                      style="width: 100%"
                      v-model:value="modelRef.extra_config.completedTime"
                      valueFormat="YYYY-MM-DD"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 6">
                  <a-form-item label="标准层高">
                    <a-input
                      placeholder="请输入标准层高"
                      v-model:value="modelRef.extra_config.floor_height"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 6">
                  <a-form-item label="物业">
                    <a-input v-model:value="modelRef.extra_config.ownerName" />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 6">
                  <a-form-item label="物业费">
                    <a-input
                      v-model:value="modelRef.extra_config.ownerCost"
                      placeholder="例：5 元/㎡/月"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 6">
                  <a-form-item label="车位数量">
                    <a-input
                      placeholder="例：200个"
                      v-model:value="modelRef.extra_config.parkingNumber"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 6">
                  <a-form-item label="车位月租金">
                    <a-input
                      placeholder="请输入车位月租金"
                      v-model:value="modelRef.extra_config.parkingMonthlyRent"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 6">
                  <a-form-item label="空调">
                    <a-input
                      placeholder="例：中央空调"
                      v-model:value="modelRef.extra_config.airConditioner"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 6">
                  <a-form-item label="空调费">
                    <a-input
                      placeholder="例：按用量计算"
                      v-model:value="modelRef.extra_config.airConditionerCost"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 6">
                  <a-form-item label="空调开放时间">
                    <a-input
                      placeholder="例：夏冬8:00-20:00"
                      v-model:value="modelRef.extra_config.airConditionerTime"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 6">
                  <a-form-item label="电梯">
                    <a-input
                      placeholder="例：4台"
                      v-model:value="modelRef.extra_config.elevator"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 6">
                  <a-form-item label="网络">
                    <a-input
                      placeholder="例：电信光纤"
                      v-model:value="modelRef.extra_config.network"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 6">
                  <a-form-item label="入驻企业">
                    <a-input
                      v-model:value="modelRef.extra_config.settledEnterprise"
                    />
                  </a-form-item>
                </a-col>

                <a-col :span="$store.getters.isMobile ? 24 : 6">
                  <a-form-item label="招商时间">
                    <a-input
                      placeholder="例：早8点到晚7点"
                      v-model:value="
                        modelRef.extra_config.attractInvestmentTime
                      "
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 6">
                  <a-form-item label="招商人员">
                    <DepartmentPositionForm
                      :departmentName="departmentName"
                      :postName="postName"
                      :detailData="detailData"
                      @closeCircle="closeCircleClick"
                      @onSuccess="onSuccess"
                    />
                    <!-- <a-row
                      :wrap="false"
                      class="investmen-personne"
                      @click="investmentPersonnelClick"
                    >
                      <span v-if="!departmentName" style="color: #bfbfbf"
                        >请选择人员</span
                      >
                      <a-row v-else style="width: 100%" :gutter="[4, 4]">
                        <a-col>
                          <a-col
                            class="tag-style"
                            style="padding: 0px 7px"
                            v-if="departmentName"
                          >
                            <span>部门：</span>
                            <span>{{ departmentName }}</span>
                          </a-col>
                          <span v-else style="color: #bfbfbf">请选择</span>
                        </a-col>
                        <a-col>
                          <a-col
                            class="tag-style"
                            style="padding: 0px 7px"
                            v-if="postName.length > 0"
                          >
                            <span>岗位：</span>
                            <span>{{ postName.join("，") }}</span>
                          </a-col>
                          <span v-else style="color: #bfbfbf">请选择</span>
                        </a-col>
                        <a-col
                          class="closeCircle"
                          @click.stop="closeCircleClick"
                          ><CloseCircleOutlined
                        /></a-col>
                      </a-row>
                    </a-row> -->
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 6">
                  <a-form-item label="上传视频">
                    <a-upload
                      v-model:file-list="fileListVideo"
                      name="file"
                      :multiple="false"
                      :action="$utils.fileAction"
                      :headers="{ 'org-token': $store.getters.token }"
                      @change="handleChange"
                      :before-upload="beforeUpload"
                      accept="video/mp4"
                    >
                      <a-button>
                        <UploadOutlined />
                        上传文件
                      </a-button>
                      <div class="Video">支持上传10M以内的mp4格式的视频</div>
                    </a-upload>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-collapse-panel>
          </a-collapse>
        </a-card>
        <a-card
          title="房源状态颜色配置"
          :bordered="false"
          class="housing-status mt-20"
        >
          <a-row
            :wrap="true"
            :gutter="[12, 12]"
            :style="{
              marginRight: $store.getters.isMobile ? undefined : '100px',
            }"
          >
            <a-col
              :xs="12"
              :md="6"
              :xxl="4"
              v-for="(item, index) of modelRef.room_status_color"
              :key="'list_' + index"
            >
              <a-card class="box">
                <color-picker
                  v-model:hex="item.color"
                  :show-opacity="false"
                  :btn-style="{
                    width: '40px',
                    height: '40px',
                    margin: '0 auto',
                  }"
                />
                <div class="title">{{ item.title }}</div>
                <div
                  class="del"
                  @click="handleStatusDel(index)"
                  v-if="item.isCustom == 1"
                >
                  <CloseCircleFilled />
                </div>
              </a-card>
            </a-col>
            <a-col
              :xs="12"
              :md="6"
              :xxl="4"
              key="add_new_status"
              @click="statusAddVisible = true"
            >
              <a-card class="box add">
                <PlusOutlined style="font-size: 36px" />
                <div class="title">新建</div>
              </a-card>
            </a-col>
          </a-row>
        </a-card>
        <a-card
          :tab-list="visualTabList"
          :active-tab-key="currentVisualTab"
          @tabChange="(key) => onVisualTabChange(key)"
          :bordered="false"
          class="mt-20"
        >
          <template v-if="currentVisualTab == '3d'">
            <a-upload
              v-model:file-list="fbxList"
              name="file"
              :multiple="false"
              :action="$utils.fileAction"
              :headers="{ 'org-token': $store.getters.token }"
              :showUploadList="true"
              @change="uploadFbx"
              accept=".doc"
              :data="{ dir: 'org_village_fbx' }"
            >
              <a-button v-if="!fbxList.length">
                <UploadOutlined />
                点击上传
              </a-button>
            </a-upload>
          </template>

          <template v-if="currentVisualTab == 'visualPic'">
            <a-upload
              v-model:file-list="visualPicList"
              name="file"
              key="visualPicList"
              :multiple="false"
              :action="$utils.fileAction"
              :headers="{ 'org-token': $store.getters.token }"
              :showUploadList="true"
              @change="handleVisualPicUpload"
              accept="image/jpg,image/jpeg,image/png"
              :data="{ dir: 'org_village' }"
            >
              <a-button v-if="!visualPicList.length">
                <UploadOutlined />
                点击上传
              </a-button>
            </a-upload>
          </template>
        </a-card>
      </a-form>
    </section>
    <section class="footer">
      <a-button size="large" class="mr-20" @click="clearBtn">取消</a-button>
      <a-button
        type="primary"
        size="large"
        @click="onSubmit"
        :loading="submitLoading"
        >保存</a-button
      >
    </section>
    <building-add
      :visible="buildingAddVisble"
      :sort="buildingSort"
      :detail="buildingDetail"
      @cancel="hanldeBuildingAddCancel"
      @confirm="hanldeBuildingAddConfirm"
    ></building-add>
    <!-- 房源标签 -->
    <EditTag
      @cancel="editTagClose"
      @success="editSuccess"
      :visible="editVisible"
      title="项目标签"
      :requestUrl="{
        color: '/manage/taglib/village/color',
        save: '/manage/taglib/village',
        detail: '/manage/taglib/village/get',
      }"
    ></EditTag>
    <!-- 新建房源状态 -->
    <a-modal
      v-model:visible="statusAddVisible"
      title="添加自定义状态"
      @ok="handleStatusAddOk"
      @cancel="handleStatusAddCancel"
      centered
    >
      <a-row :gutter="12">
        <a-col :span="$store.getters.isMobile ? undefined : 5" class="lh-30"
          >限制条件:</a-col
        >
        <a-col :span="$store.getters.isMobile ? undefined : 8">
          <a-radio-group v-model:value="addForm.type">
            <a-radio-button value="vacant">空置</a-radio-button>
            <a-radio-button value="expire">距到期</a-radio-button>
          </a-radio-group>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 6 : 8">
          <a-input-number
            class="w-100p"
            v-model:value="addForm.limit"
            :min="1"
            placeholder="请输入限制范围"
          />
        </a-col>
        <a-col :span="$store.getters.isMobile ? undefined : 2" class="lh-32"
          >日</a-col
        >
      </a-row>
      <a-row :gutter="12" class="mt-20">
        <a-col :span="$store.getters.isMobile ? undefined : 5" class="lh-32">
          状态颜色：
        </a-col>
        <a-col :span="$store.getters.isMobile ? 8 : 6">
          <color-picker
            v-model:hex="addForm.color"
            :show-opacity="false"
            :btn-style="{
              width: '100px',
              height: '32px',
            }"
          />
        </a-col>
        <a-col :span="$store.getters.isMobile ? 8 : 4" class="lh-32">{{
          addForm.color
        }}</a-col>
      </a-row>
    </a-modal>
  </div>
</template>

<script>
import {
  computed,
  defineComponent,
  nextTick,
  reactive,
  ref,
  toRaw,
  toRefs,
  watch,
} from "vue";
import { Form, message } from "ant-design-vue";
import {
  PlusOutlined,
  UploadOutlined,
  CloseCircleFilled,
  QuestionCircleOutlined,
  CloseOutlined,
  PictureOutlined,
  CloseCircleOutlined,
} from "@ant-design/icons-vue";
import request from "../../../common/utils/request";
import utils from "../../../common/utils/utils";
import BuildingAdd from "./modules/BuildingAdd.vue";
import { useRouter, useRoute } from "vue-router";
import EditTag from "../../../components/Tag/add.vue";
import store from "../../../store";
import BLCOMMON from "bl-common-vue3";
import { DepartmentPositionForm } from "bl-common-vue3";

import ImageCropper from "../../../components/ImageCropper/index.vue";
import draggable from "vuedraggable";
import ColorPicker from "colorpicker-v3";
require("colorpicker-v3/dist/style.css");

const useForm = Form.useForm;

const DEFAULT_COLOR = "#a9dcfd";

export default defineComponent({
  name: "BuildingProjectEdit",
  components: {
    PlusOutlined,
    BuildingAdd,
    EditTag,
    UploadOutlined,
    ColorPicker,
    CloseCircleFilled,
    QuestionCircleOutlined,
    draggable,
    ImageCropper,
    CloseOutlined,
    DepartmentPositionForm,
    VNodes: (_, { attrs }) => {
      return attrs.vnodes;
    },
    PictureOutlined,
  },
  setup() {
    const $router = useRouter();
    const $route = useRoute();
    const id = ref(0);

    const systemOnIntranet = computed(() => {
      return store.getters?.basicConfig?.system_on_intranet;
    });

    const goBack = () => {
      if (window.history.state.back) {
        $router.back();
      } else {
        $router.replace({
          name: "villageList",
        });
      }
    };

    const title = computed(() => {
      return id.value
        ? `编辑${BLCOMMON.utils.L("项目")}`
        : `新增${BLCOMMON.utils.L("项目")}`;
    });

    const state = reactive({
      logoList: [],
      fbxList: [],
      detail: {},
      defaultColor: DEFAULT_COLOR,
      statusAddVisible: false,
      treeData: [],
      departmentTree: [],
      sortList: [],

      // 上传视频
      fileListVideo: [],

      visualTabList: [
        {
          key: "3d",
          tab: "3D模型",
        },
        {
          key: "visualPic",
          tab: "2D鸟瞰图",
        },
      ],
      currentVisualTab: "3d",
      visualPicList: [],
      departmentPositionVisible: false,

      departmentName: "",
      postName: [],
      detailData: {},

      submitLoading: false,
    });

    // 房源状态管理

    const addForm = reactive({
      type: "vacant",
      limit: "",
      color: DEFAULT_COLOR,
    });

    const handleStatusAddOk = () => {
      if (addForm.limit) {
        const index = modelRef.room_status_color.findIndex(
          (item) => item.type == addForm.type && item.limit == addForm.limit
        );
        if (index > -1) {
          message.warning("您已经添加过此房源状态！");
          return;
        }
        let newItem = { ...addForm, isCustom: 1 };
        if (newItem.type == "vacant") {
          newItem.title = `空置${newItem.limit}日以上`;
        } else {
          newItem.title = `${newItem.limit}日内到期`;
        }
        modelRef.room_status_color.push(newItem);
        handleStatusAddCancel();
      } else {
        message.warning("您还未填写限制条件天数！");
      }
    };
    const handleStatusAddCancel = () => {
      addForm.type = "vacant";
      addForm.limit = "";
      addForm.color = DEFAULT_COLOR;
      state.statusAddVisible = false;
    };
    const handleStatusDel = (index) => {
      modelRef.room_status_color.splice(index, 1);
    };
    const imageCropper = ref(null);
    const getDetail = () => {
      request
        .get("/village", "/project/manage/get", {
          id: id.value,
        })
        .then((res) => {
          if (!res.list.extra_config) {
            res.list.extra_config = {};
          }
          state.detail = res.list;
          setModelRef(res.list);
          if (!systemOnIntranet.value) {
            modelRef.address = res.list.address;
          } else {
            modelRef.address = "无网络，无法选择地址";
          }

          // 部门
          if (res.list.extra_config.department_id) {
            state.departmentName = res.list.extra_config.department_txt;
            state.detailData.departmentSelectedNodes = {
              id: res.list.extra_config.department_id,
              name: res.list.extra_config.department_txt,
            };
          } else {
            state.departmentName = "";
            state.detailData.departmentSelectedNodes = {};
          }

          // 岗位
          if (res.list.extra_config.post_id) {
            let newArray = res.list.extra_config.post_id.map((value, index) => {
              return {
                id: value,
                name: res.list.extra_config.post_txt.split("，")[index],
              };
            });
            state.detailData.postsSelectedNodes = newArray;
            state.postName = res.list.extra_config.post_txt.split("，");
          } else {
            state.detailData.postsSelectedNodes = [];
            state.postName = "";
          }

          if (res.list.extra_config && res.list.extra_config.iamges) {
            imageCropper.value.detailsImage(res.list.extra_config.iamges);
            // imageCropper.value.detailsImage(res.list.extra_config.iamges);
            state.sortList = res.list.extra_config.iamges.map((item) => {
              return {
                url: item,
              };
            });
            modelRef.extra_config.iamges = res.list.extra_config.iamges;
            modelRef.logo = res.list.extra_config.iamges[0];
          }
          if (res.list.video) {
            state.fileListVideo = [
              {
                uid: "1",
                name: res.list.video,
                status: "done",
                url: res.list.video,
              },
            ];
            modelRef.video = res.list.video;
          }
          if (
            state.detail.room_status_color &&
            state.detail.room_status_color.length
          ) {
            modelRef.room_status_color = state.detail.room_status_color;
          } else {
            modelRef.room_status_color = store.getters.defaultHousingStatus;
          }
          district_txt = state.detail.district_txt;
          if (state.detail.logo) {
            logo = state.detail.logo;
            state.logoList = [
              {
                uid: "1",
                name: state.detail.logo,
                status: "done",
                url: state.detail.logo,
              },
            ];
          }
          if (state.detail.three_dimensional_file) {
            state.fbxList = [
              {
                uid: "2",
                name: state.detail.three_dimensional_file,
                status: "done",
                url: state.detail.three_dimensional_file,
              },
            ];

            state.visualTabList[0].tab = "3D模型(已上传)";
          }
          if (state.detail.dimensional_bg_img) {
            state.visualPicList = [
              {
                uid: "2",
                name: state.detail.dimensional_bg_img,
                status: "done",
                url: state.detail.dimensional_bg_img,
              },
            ];

            state.visualTabList[1].tab = "2D鸟瞰图(已上传)";
          }
          if (state.detail.province_id) {
            getArea();
          } else {
            utils.getAreaOptions(1).then((res) => {
              areaOptions.value = res;
            });
          }
        });
    };

    const modelRef = reactive({
      name: "",
      short_name: "",
      describe: "",
      address: !systemOnIntranet.value ? "" : "无网络，无法选择地址",
      area: [], // 所属地区
      tag_id_arr: [],
      lat: 0,
      lng: 0,
      room_status_color: store.getters.defaultHousingStatus,
      vr_link: "",
      sort: "",
      extra_config: {
        completedTime: "",
        floor_height: "",
        ownerName: "",
        ownerCost: "",
        parkingNumber: "",
        parkingMonthlyRent: "",
        airConditioner: "",
        airConditionerCost: "",
        airConditionerTime: "",
        elevator: "",
        network: "",
        settledEnterprise: "",
        post_id: undefined,
        department_id: undefined,
        attractInvestmentTime: "",
        iamges: [],
      },
      video: "",
      user_show: 1
    });
    const clearBtn = () => {
      $router.back();
      add.value = 0;
    };
    const setModelRef = (state) => {
      for (let key in state) {
        modelRef[key] = state[key];
      }
    };
    const rulesRef = reactive({
      name: [
        { required: true, message: `${BLCOMMON.utils.L("项目名称")}为必填项` },
      ],
      short_name: [
        {
          required: true,
          message: `${BLCOMMON.utils.L("项目简称")}缩写为必填项`,
        },
      ],
      address: [
        {
          required: !systemOnIntranet.value,
          message: `${BLCOMMON.utils.L("项目")}详细地址为必填项`,
        },
      ],
      area: [
        {
          required: true,
          validator: (rules, value) => areaValidator(value),
          trigger: "blur",
        },
      ],
    });
    const areaValidator = async (value) => {
      if (!value.length) {
        return Promise.reject(`${BLCOMMON.utils.L("项目")}归属地区为必填项`);
      }
      if (value.length < 3) {
        return Promise.reject(
          `${BLCOMMON.utils.L("项目")}归属地区需精确到市级或区及以下`
        );
      }
      return Promise.resolve();
    };

    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    const onSubmit = () => {
      validate().then(() => {
        if ((!modelRef.lat || !modelRef.lng) && !systemOnIntranet.value) {
          message.warning("详细地址需要点击搜索按钮在地图上选取位置~");
          return;
        }

        let params = { ...toRaw(modelRef), needMsg: true };
        params.district_txt = district_txt;
        params.province_id = params.area[0];
        params.city_id = params.area[1];
        params.district_id = params.area[2];
        params.street_id = params.area[3];
        params.community_id = params.area[4];
        delete params.area;
        params.buildArr = [
          {
            name: "01",
            number: "01",
            sort: "0",
            buildList: buildingList.value,
          },
        ];
        // params.logo = logo;
        if (state.fbxList.length > 0) {
          params.three_dimensional_file = state.fbxList[0].url;
        } else {
          params.three_dimensional_file = "";
        }
        if (state.visualPicList.length > 0) {
          params.dimensional_bg_img = state.visualPicList[0].url;
        } else {
          params.dimensional_bg_img = "";
        }
        console.log("paramsparamsparams", params);
        let requestMethod = "post";
        if (id.value) {
          params.id = id.value;
          params.type = state.detail.type;
          requestMethod = "put";
        } else {
          params.type = $route.query.type;
        }
        state.submitLoading = true;
        request[requestMethod]("/village", "/project/manage", params)
          .then((res) => {
            if (res) {
              if (!id.value) {
                message.success(
                  `${BLCOMMON.utils.L("项目")}添加成功，需要在左上角选择项目哦~`
                );
                store.dispatch("SetBuildingVisible", true);
              } else {
                message.success(res.msg || "保存成功！");
              }
              $router.back();
            }
            state.submitLoading = false;
          })
          .catch(() => {
            state.submitLoading = false;
          });
      });
    };

    // 所属地区
    const areaOptions = ref([]);
    // 动态加载省市区信息
    const loadAreaData = (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      console.log(targetOption);
      utils
        .getAreaOptions(targetOption.level + 1, {
          id: targetOption.value,
        })
        .then((res) => {
          if (res.length) {
            targetOption.children = res;
          } else {
            targetOption.isLeaf = true;
          }
          targetOption.loading = false;
        });
    };
    // 监听省市区选择
    let district_txt = "";
    const areaSelectChange = (value, selectedOptions) => {
      if (selectedOptions.length >= 3) {
        let areaTxtArr = selectedOptions.map((item) => item.label);
        district_txt = areaTxtArr.join(",");
      } else {
        district_txt = "";
      }
    };
    // 加载已选择列表
    const getArea = () => {
      const { province_id, city_id, district_id, street_id, community_id } =
        state.detail;
      if (province_id) {
        modelRef.area.push(province_id);
        utils.getAreaOptions(1).then((list) => {
          areaOptions.value = list;
          let index = list.findIndex((item) => item.value == province_id);
          if (city_id && index > -1) {
            modelRef.area.push(city_id);
            let province = areaOptions.value[index];
            utils.getAreaOptions(2, { id: province_id }).then((cityList) => {
              if (cityList.length) {
                province.children = cityList;
                index = cityList.findIndex((item) => item.value == city_id);
                if (district_id && index > -1) {
                  modelRef.area.push(district_id);
                  let city = province.children[index];
                  utils
                    .getAreaOptions(3, { id: city_id })
                    .then((districtList) => {
                      if (districtList.length) {
                        city.children = districtList;
                        index = districtList.findIndex(
                          (item) => item.value == district_id
                        );
                        if (street_id && index > -1) {
                          modelRef.area.push(street_id);
                          let district = city.children[index];
                          utils
                            .getAreaOptions(4, { id: district_id })
                            .then((streetList) => {
                              if (streetList.length) {
                                district.children = streetList;
                                index = streetList.findIndex(
                                  (item) => item.value == street_id
                                );
                                if (community_id && index > -1) {
                                  modelRef.area.push(community_id);
                                  let street = district.children[index];
                                  utils
                                    .getAreaOptions(5, { id: street_id })
                                    .then((communityList) => {
                                      if (communityList.length) {
                                        street.children = communityList;
                                      } else {
                                        street.isLeaf = true;
                                      }
                                    });
                                }
                              } else {
                                district.isLeaf = true;
                              }
                            });
                        }
                      } else {
                        city.isLeaf = true;
                      }
                    });
                }
              } else {
                province.isLeaf = true;
              }
            });
          }
        });
      }
    };

    // 项目标签
    const editVisible = ref(false);
    const addTag = () => {
      console.log("添加");
      editVisible.value = true;
    };
    const editTagClose = () => {
      editVisible.value = false;
    };
    const add = ref(0);
    const editSuccess = () => {
      editTagClose();
      getProjectTags();
      add.value = 1;
    };
    const projectTags = ref([]);
    const getProjectTags = () => {
      request.get("/org", "/manage/taglib/village").then((res) => {
        if (res.list.length) {
          if (add.value == 1) {
            modelRef.tag_id_arr.push(res.list[0].id);
          }
          projectTags.value = res.list.map((item) => ({
            value: item.id,
            label: item.name,
          }));
        }
      });
    };
    // 岗位接口
    const postList = () => {
      request.get("/org", "/post/list").then((res) => {
        state.treeData = utils.transListToTreeData(res.list, "");
      });
    };
    // 部门接口
    const departmentList = () => {
      request.get("/org", "/department/index", { withUser: 0 }).then((res) => {
        state.departmentTree = res.list;
      });
    };

    watch(
      [() => $route.name, () => $route.query.id],
      ([name, id], [preName, preId]) => {
        if (name == "projectEdit" && id != preId) {
          init();
        }
      }
    );

    const init = () => {
      id.value = $route.query.id || 0;

      if (id.value) {
        getDetail();
      } else {
        utils.getAreaOptions(1).then((res) => {
          areaOptions.value = res;
        });
      }
      getProjectTags();
      postList();
      departmentList();
    };

    const mapAddress = ref("");
    const onAddressSearch = () => {
      if (systemOnIntranet.value) {
        return;
      }
      if (!district_txt) {
        message.warning("请先选择项目所属地区");
        return;
      }
      mapAddress.value = district_txt; // + "," + modelRef.address;
      let info = {
        type: "selectMap",
        visible: true,
        mapAddress: modelRef.address,
        mapDistrict: mapAddress.value,
        success: (detail) => {
          const { location } = detail;
          modelRef.address = location.name;
          modelRef.lat = location.latLng.lat;
          modelRef.lng = location.latLng.lng;
        },
      }
      if (modelRef.lat && modelRef.lng) {
        info.mapLatLng = {
          lat: modelRef.lat,
          lng: modelRef.lng,
        }
      }
      window.microApp.forceDispatch(info)
    };

    // 添加楼栋
    const buildingAddVisble = ref(false);
    const buildingList = ref([]);
    // buildingSort也为buildingList序号index
    const buildingSort = ref(0);
    const buildingDetail = ref(null);
    const addBuilding = (index) => {
      if (buildingList.value.length === 3) {
        utils.modalConfirm({
          content: "更多房源导入请在“房源管理”中使用excel表格导入。",
          centered: true,
        });
        return;
      }
      if (index || index == 0) {
        buildingDetail.value = buildingList.value[index];
        buildingSort.value = index;
      } else {
        buildingDetail.value = null;
        buildingSort.value = buildingList.value.length + 1;
      }
      buildingAddVisble.value = true;
    };
    const hanldeBuildingAddCancel = () => {
      buildingAddVisble.value = false;
    };
    const hanldeBuildingAddConfirm = (buildingData) => {
      // console.log("-----hanldeBuildingAddConfirm", buildingData);
      if (buildingData.sort < buildingList.value.length) {
        buildingList.value[buildingData.sort] = buildingData;
      } else {
        buildingList.value.push(buildingData);
      }
      hanldeBuildingAddCancel();
    };

    // 图片上传
    let logo = "";
    const uploadFbx = (info) => {
      let resFileList = [...info.fileList];
      let result = resFileList.slice(-1);
      result = result[0];
      if (result && result.response) {
        if (result.response.code == 1000) {
          state.fbxList = resFileList;
        } else {
          message.warning(result.response.msg);
        }
      }
    };
    const uploadLogo = (info) => {
      let resFileList = [...info.fileList];
      let result = resFileList.slice(-1);
      result = result[0];
      if (result && result.response) {
        if (result.response.code == 1000) {
          logo = result.response.data.fileUrl;
          state.logoList = resFileList;
          previewImage.value = resFileList[0].response.data.fileUrl;
        } else {
          state.logoList = [];
          message.warning(result.response.msg);
        }
      }
    };
    const handlePreview = () => {
      previewVisible.value = true;
    };
    const previewVisible = ref(false);
    const previewImage = ref("");
    const handleCancel = () => {
      previewVisible.value = false;
    };
    const removeClick = (file) => {
      state.logoList = [];
      logo = "";
    };

    // 折叠面板
    const activeKey = ref([]);
    // 上传裁剪图片
    const cropSuccess = (fileList) => {
      modelRef.extra_config.iamges = fileList.map((item) => item.url);
      // if (modelRef.extra_config.iamges.length) {
      //   state.sortList = state.sortList.concat(fileList);
      //   return;
      // }
      state.sortList = fileList;
    };
    // 移除裁剪图片
    const removeImage = (fileList) => {
      setTimeout(() => {
        let url = [];
        fileList.forEach((item) => {
          if (!item.status) {
            url.push(item.url);
          }
        });
        modelRef.extra_config.iamges = url;
      }, 0);
    };
    const deleClick = (index) => {
      state.sortList.splice(index, 1);
      modelRef.extra_config.iamges = state.sortList.map((item) => item.url);
      imageCropper.value.deleteImage(modelRef.extra_config.iamges);
      if (state.sortList.length == 0) {
        modelRef.logo = "";
      }
    };
    watch(
      () => state.sortList,
      (val) => {
        if (val.length) {
          modelRef.extra_config.iamges = val.map((item) => item.url);
          modelRef.logo = val[0].url;
        }
      }
    );
    const drag = ref(false);
    const dragOptions = computed(() => {
      return {
        animation: 200,
        group: "description",
        disabled: false,
        ghostClass: "ghost",
      };
    });

    // 上传视频
    const handleChange = (info) => {
      if (info.file.status == "removed") {
        modelRef.video = "";
        state.fileListVideo = [];
      }
      let resFileList = [...info.fileList];
      let result = resFileList.slice(-1);
      result = result[0];
      if (result && result.response) {
        if (result.response.code == 1000) {
          state.fileListVideo = resFileList.slice(-1);
          modelRef.video = resFileList.slice(-1)[0].response.data.fileUrl;
        } else {
          message.warning(result.response.msg);
        }
      }
    };

    const beforeUpload = (file) => {
      const isLt2M = file.size / 1024 / 1024 <= 10;
      if (!isLt2M) {
        message.error("视频仅支持 10MB 以内");
      }

      return isLt2M;
    };

    const onVisualTabChange = (key) => {
      state.currentVisualTab = key;
    };

    const handleVisualPicUpload = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList = resFileList.slice(-1);
        resFileList = resFileList.map((file) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
              state.visualPicList = resFileList;
            } else {
              message.warning(file.response.msg);
            }
          }
        });
      }
    };

    const investmentPersonnelClick = () => {
      if (
        modelRef.extra_config.department_id &&
        modelRef.extra_config.post_id
      ) {
        state.detailData.departmentSelectedNodes = {
          id: modelRef.extra_config.department_id,
          name: state.departmentName,
        };
        let newArray = modelRef.extra_config.post_id.map((value, index) => {
          return {
            id: value,
            name: state.postName[index],
          };
        });
        state.detailData.postsSelectedNodes = newArray;
      } else {
        state.detailData = {};
      }

      state.departmentPositionVisible = true;
    };

    const onClose = () => {
      state.departmentPositionVisible = false;
    };

    const onSuccess = (data) => {
      modelRef.extra_config.department_id = data.department_id;
      modelRef.extra_config.post_id = data.post_id;
      state.departmentName = data.departmentName;
      state.postName = data.postName;
      if (
        modelRef.extra_config.department_id &&
        modelRef.extra_config.post_id
      ) {
        state.detailData.departmentSelectedNodes = {
          id: modelRef.extra_config.department_id,
          name: state.departmentName,
        };
        let newArray = modelRef.extra_config.post_id.map((value, index) => {
          return {
            id: value,
            name: state.postName[index],
          };
        });
        state.detailData.postsSelectedNodes = newArray;
      } else {
        state.detailData = {};
      }
    };

    const closeCircleClick = () => {
      modelRef.extra_config.department_id = undefined;
      modelRef.extra_config.post_id = undefined;
      state.departmentName = "";
      state.postName = [];
      state.detailData = {};
    };

    init();

    return {
      ...toRefs(state),
      id,
      title,
      modelRef,
      validateInfos,
      areaOptions,
      loadAreaData,
      areaSelectChange,
      projectTags,
      onAddressSearch,
      mapAddress,
      onSubmit,
      buildingAddVisble,
      addBuilding,
      hanldeBuildingAddCancel,
      hanldeBuildingAddConfirm,
      buildingList,
      buildingSort,
      buildingDetail,
      uploadFbx,
      uploadLogo,
      addTag,
      editVisible,
      editSuccess,
      editTagClose,
      clearBtn,
      addForm,
      handleStatusAddOk,
      handleStatusAddCancel,
      handleStatusDel,
      handlePreview,
      handleCancel,
      previewVisible,
      previewImage,
      removeClick,
      activeKey,
      replaceFields: {
        children: "children",
        title: "name",
        key: "id",
        value: "id",
      },
      replaceFieldsDepartment: {
        children: "subcat",
        title: "name",
        key: "id",
        value: "id",
      },
      cropSuccess,
      cropperOptions: {
        autoCrop: true, //是否默认生成截图框
        // autoCropWidth: 200, //默认生成截图框宽度
        // autoCropHeight: 200, //默认生成截图框高度
        fixedBox: false, //是否固定截图框大小 不允许改变
        previewsCircle: false, //预览图是否是圆形
        title: "图片裁剪", //模态框上显示的标题
        imageUrl: "",
      },
      removeImage,
      imageCropper,
      dragOptions,
      drag,
      deleClick,
      handleChange,
      beforeUpload,
      goBack,

      namePlaceholder: BLCOMMON.utils.L("项目名称"),
      placeholderShortName: BLCOMMON.utils.L("项目简称"),
      placeholderEextarea: BLCOMMON.utils.L("项目简介"),
      placeholderTag: "请选择" + BLCOMMON.utils.L("项目") + "标签",
      placeholderPost: `请选择${BLCOMMON.utils.L("项目")}负责招商的岗位`,
      placeholderDepartment: `请选择${BLCOMMON.utils.L("项目")}负责招商的部门`,

      onVisualTabChange,
      handleVisualPicUpload,

      investmentPersonnelClick,
      onSuccess,
      onClose,
      closeCircleClick,
      systemOnIntranet,
    };
  },
});
</script>

<style lang="less" scoped>
.projectEdit {
  height: 100%;
  display: flex;
  flex-direction: column;
  &.isMobile {
    :deep(.ant-page-header-back) {
      display: none;
    }
  }
  .header {
    height: 70px;
    background: #f7f7f7;
  }
  .content {
    flex: 1;
    margin: 10px;
    max-height: calc(~"100%- 160px");
    overflow-y: auto;

    .add-btn {
      width: 80px;
      height: 80px;
      border: 1px dashed #ccc;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      font-size: 24px;
      cursor: pointer;
    }
    .building-card {
      width: 80px;
      height: 80px;
      box-shadow: 0px 0px 6px 3px #f1f1f1;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20px;
      flex-direction: column;
      cursor: pointer;
      padding: 10px;
      box-sizing: border-box;
      overflow: hidden;
      .title {
        width: 100%;
        font-weight: bold;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: break-all;
      }
      .desc {
        margin-top: 5px;
        color: rgba(0, 0, 0, 0.4);
      }
    }

    .housing-status {
      .box {
        text-align: center;
        position: relative;
        .status-color {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          margin: 0 auto;
        }
        .title {
          font-size: 14px;
          margin-top: 10px;
          color: #000;
        }
        .del {
          position: absolute;
          right: 0px;
          top: 0px;
          width: 30px;
          height: 30px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 18px;
          color: red;
          cursor: pointer;
        }
      }
      .add {
        cursor: pointer;
        color: #666;
        height: 100%;
        .title {
          color: #666 !important;
        }
      }
    }
  }
  .footer {
    height: 70px;
    display: flex;
    justify-content: flex-end;
    background: #f7f7f7;
    align-items: center;
    padding: 0 20px;
  }
  .collapseTitle {
    font-size: 16px;
    margin-right: 10px;
  }
  .collapseTitleSub {
    color: #929292;
    font-size: 14px;
  }
  :deep(.ant-collapse-borderless) {
    background: #ffff;
    padding: 0;
  }
  :deep(.ant-collapse-header) {
    padding: 12px 0px !important ;
  }
  .list-group {
    // min-height: 20px;
    display: flex;
    flex-wrap: wrap;
  }

  .list-group-item {
    position: relative;
    cursor: move;
    font-size: 16px;
    margin-right: 20px;
    margin-bottom: 14px;
    width: 183px;
    border: 1px solid #ccc;
    .imgae {
      width: 100%;
      height: 100%;
    }
    .title {
      margin-left: 20px;
    }
  }
  .list-group-icon {
    display: none;
  }
  .list-group-item:hover {
    .list-group-icon {
      display: block;
      position: absolute;
      top: -8px;
      right: -8px;
      width: 20px;
      height: 20px;
      background: #000;
      opacity: 0.5;
      border-radius: 50%;
      .icon {
        position: absolute;
        top: 2px;
        right: 2px;
        color: #ffff;
      }
    }
    .list-group-icon {
      cursor: pointer;
    }
  }
  .Video {
    margin-top: 10px;
    color: #8d8d8d;
  }

  .detail-address {
    position: relative;
    display: inline-block;
    width: 100%;
    padding: 4px 11px;
    font-size: 14px;
    line-height: 20px;
    background-color: #fff;
    background-image: none;
    border: 1px solid #d9d9d9;
    border-radius: 2px;
    color: rgba(0, 0, 0, 0.85);
    cursor: pointer;
    .placeholder {
      color: rgba(0, 0, 0, 0.32);
    }
  }
  :deep(.ant-select-multiple .ant-select-selection-item-remove) {
    display: none;
  }
  .investmen-personne {
    width: 100%;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    padding: 5px;
    padding-bottom: 4px;
    padding-right: 18px;
    cursor: pointer;
    // font-size: 12px;
    .tag-style {
      border-radius: 3px;
      border: 1px solid #d9d9d9;
      background: #f5f5f5;
      // padding: 0 2px;
      font-size: 12px;
    }
    .closeCircle {
      position: absolute;
      right: 2px;
      top: 0;
      height: 100%;
      display: flex;
      align-items: center;
      font-size: 16px;
      cursor: pointer;
    }
  }
}
</style>
